package com.weichen.studentgameexchange.game.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weichen.studentgameexchange.game.common.Result;
import com.weichen.studentgameexchange.game.dao.UserGameGradeMapper;
import com.weichen.studentgameexchange.game.entity.Game;
import com.weichen.studentgameexchange.game.entity.UserGameGrade;
import com.weichen.studentgameexchange.game.entity.vo.GradeVo;
import com.weichen.studentgameexchange.game.feign.MemberFeignClient;
import com.weichen.studentgameexchange.game.service.IUserGameGradeService;
import com.weichen.studentgameexchange.member.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 惟尘
 * @since 2025-02-01
 */
@Service
public class UserGameGradeServiceImpl extends ServiceImpl<UserGameGradeMapper, UserGameGrade> implements IUserGameGradeService {

    @Autowired
    UserGameGradeMapper userGameGradeMapper;
    @Autowired
    MemberFeignClient memberFeignClient;

    @Override
    public Page<GradeVo> adminPage(Integer page, Integer size) {
        Page<UserGameGrade> gradePage = new Page<>(page, size);
        LambdaQueryWrapper<UserGameGrade> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(UserGameGrade::getGradeId);
        Page<UserGameGrade> selectPage = userGameGradeMapper.selectPage(gradePage, lambdaQueryWrapper);
        List<UserGameGrade> records = selectPage.getRecords();

        // 对 gameIds 和 userIds 进行去重处理
        List<Long> gameIds = records.stream()
                .map(UserGameGrade::getGameId)
                .distinct()
                .toList();
        List<Long> userIds = records.stream()
                .map(UserGameGrade::getUserId)
                .distinct()
                .toList();

        // 批量查询游戏信息并构建映射（去重后无重复键）
        Map<Long, String> gameNameMap = new HashMap<>();
        if (!gameIds.isEmpty()) {
            gameNameMap = Db.lambdaQuery(Game.class)
                    .in(Game::getGameId, gameIds)
                    .list()
                    .stream()
                    .collect(Collectors.toMap(Game::getGameId, Game::getGameName));
        }

        // 批量查询用户信息并构建映射（去重后无重复键）
        Map<Long, String> userNameMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            List<User> users = memberFeignClient.getUsersByIds(userIds);
            userNameMap = users.stream()
                    .collect(Collectors.toMap(User::getUserId, User::getUsername));
        }

        // 转换VO并填充关联信息
        Map<Long, String> finalGameNameMap = gameNameMap;
        Map<Long, String> finalUserNameMap = userNameMap;
        List<GradeVo> gradeVoList = records.stream().map(grade -> {
            GradeVo vo = new GradeVo();
            BeanUtils.copyProperties(grade, vo);
            vo.setGameName(finalGameNameMap.getOrDefault(grade.getGameId(), "N/A"));
            vo.setUserName(finalUserNameMap.getOrDefault(grade.getUserId(), "N/A"));
            return vo;
        }).toList();

        // 构建最终分页结果
        Page<GradeVo> resultPage = new Page<>(
                selectPage.getCurrent(),
                selectPage.getSize(),
                selectPage.getTotal()
        );
        resultPage.setRecords(gradeVoList);
        return resultPage;
    }

    @Override
    public Result userSelect(Long userId, Long gameId) {
        UserGameGrade grade = Db.lambdaQuery(UserGameGrade.class)
                .eq(UserGameGrade::getUserId, userId)
                .eq(UserGameGrade::getGameId, gameId)
                .one();
        return Result.success(grade);
    }
}
